/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.toolkit.jersey.jetty;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.inject.Inject;
import javax.servlet.ServletContext;

import org.glassfish.jersey.server.mvc.freemarker.FreemarkerConfigurationFactory;
import org.jvnet.hk2.annotations.Optional;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.cache.WebappTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Version;

public class FreemarkerConfig implements FreemarkerConfigurationFactory {

	protected final Configuration configuration;
	
	@Inject
	public FreemarkerConfig(@Optional final ServletContext servletContext){
		Version version = Configuration.VERSION_2_3_23;
		configuration = new Configuration(version);
		//configuration.setSharedVariable("cutStr", new FtlMethod());
		configuration.setDefaultEncoding("utf-8");//如果.ftl不在返回视图里，而是通过include引进去的，受此属性影响，不受@Produces影响
		//configuration.setTemplateExceptionHandler(new FtlException());
		configuration.setIncompatibleImprovements(version);
		configuration.setObjectWrapper(new DefaultObjectWrapper(version));
		final List<TemplateLoader> loaders = new ArrayList<> ();
        Properties p = new Properties();  
        try {
			p.load(FreemarkerConfig.class.getClassLoader().getResourceAsStream("freemarker.properties"));
			configuration.setSettings(p); 
	        if (servletContext != null) {
	            loaders.add(new WebappTemplateLoader(servletContext));
	        }
	        loaders.add(new ClassTemplateLoader(FreemarkerConfig.class, "/"));
            //loaders.add(new FileTemplateLoader(new File("/home/rcmu/workspace/develop/taomubox/taomu-jersery/src/main/webapps/templates/freemarker")));
        } catch (Exception e) {
        	e.printStackTrace();
        }
    	configuration.setTemplateLoader(new MultiTemplateLoader(loaders.toArray(new TemplateLoader[loaders.size()])));
	}
	
	@Override
	public Configuration getConfiguration() {
		return configuration;
	}
}

